package com.hetwen.remoteboot.activity;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.hetwen.remoteboot.R;
import com.hetwen.remoteboot.dao.MacAddrDao;
import com.hetwen.remoteboot.model.MacAddr;
import com.hetwen.remoteboot.utils.ConvertUtils;
import com.hetwen.remoteboot.utils.PromptUtils;
import com.hetwen.remoteboot.utils.StringUtils;

@SuppressWarnings("deprecation")
public class SettingsActivity extends ActionBarActivity {

	private Context context;

	private EditText et_name;
	private EditText et_mac;
	private ListView lv_addrs;

	private MacAddrDao dao;

	private List<MacAddr> addrs;
	private MacAddrsAdapter adapter;

	private String name;

	private String mac;

	private MacAddr upgradeAddr;
	private boolean isUpgrading = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_settings);
		context = this;
		initView();
		initData();
	}
	
	/**
	 * 初始化View
	 */
	private void initView() {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		et_name = (EditText) findViewById(R.id.activity_settings_et_name);
		et_mac = (EditText) findViewById(R.id.activity_settings_et_mac);
		lv_addrs = (ListView) findViewById(R.id.activity_settings_lv_addrs);
	}

	/**
	 * 初始化Data
	 */
	private void initData() {
		dao = new MacAddrDao(context);
		addrs = dao.queryAll();
		if (addrs == null) {
			addrs = new ArrayList<MacAddr>();
		}
		adapter = new MacAddrsAdapter(addrs);
		lv_addrs.setAdapter(adapter);

		// 点击后修改
		lv_addrs.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				editItem(position);
			}

		});

		// 长按后删除
		lv_addrs.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				removeItem(position);
				return false;
			}
		});
	}

	/**
	 * 保存数据
	 * @param v
	 */
	public void save(View v) {
		if (isUpgrading) {
			upgradeItem();
			isUpgrading = false;
		} else {
			insertItem();
		}
	}
	
	/**
	 * 编辑条目
	 * @param position
	 */
	private void editItem(int position) {
		MacAddr addr = (MacAddr) adapter.getItem(position);
		et_name.setText(addr.name);
		et_mac.setText(addr.mac);
		upgradeAddr = addr;
		isUpgrading = true;
	}

	/**
	 * 删除条目
	 * 
	 * @param position
	 */
	private void removeItem(int position) {
		MacAddr addr = (MacAddr) adapter.getItem(position);
		boolean isDeleted = dao.delete(addr.id);
		if (isDeleted) {
			addrs.remove(position);
			adapter.notifyDataSetChanged();
			PromptUtils.showShortToast(context, "删除成功！");
		}
	}

	/**
	 * 更新條目
	 */
	private void upgradeItem() {
		getInput();
		boolean isValid = checkInputNameAndMac();
		if (!isValid) {
			return;
		}
		upgradeAddr.name = this.name;
		upgradeAddr.mac = this.mac;
		boolean isUpgraded = dao.update(upgradeAddr);
		if(isUpgraded){
			adapter.notifyDataSetChanged();
			PromptUtils.showShortToast(context, "更新成功！");
		}
	}

	/**
	 * 新增條目
	 */
	private void insertItem() {
		getInput();
		boolean isValid = checkInputNameAndMac();
		if (!isValid) {
			return;
		}

		MacAddr macAddr = new MacAddr();
		macAddr.name = name;
		macAddr.mac = mac;
		boolean result = dao.insert(macAddr);
		if (result) {
			PromptUtils.showShortToast(context, "添加成功！");
			MacAddr queriedAddr = dao.queryByName(macAddr.name);
			if(queriedAddr != null){
				addrs.add(queriedAddr);
				adapter.notifyDataSetChanged();
			}
		} else {
			PromptUtils.showShortToast(context, "添加失败!");
		}
	}

	private void getInput() {
		name = et_name.getText().toString().trim();
		mac = et_mac.getText().toString().trim();
	}

	/**
	 * 检查用户输入
	 */
	private boolean checkInputNameAndMac() {

		if (StringUtils.isBlank(name)) {
			PromptUtils.showShortToast(context, "电脑名称不能为空！");
			et_name.setText("");
			return false;
		}

		if (StringUtils.isBlank(mac)) {
			PromptUtils.showShortToast(context, "物理地址不能为空！");
			et_mac.setText("");
			return false;
		} else {
			if (mac.length() != 12) {
				PromptUtils.showShortToast(context, "物理地址不正确！");
				et_mac.setText("");
				return false;
			} else {
				if (!ConvertUtils.isHexString(mac)) {
					PromptUtils.showShortToast(context, "物理地址不正确！");
					et_mac.setText("");
					return false;
				}
			}
		}

		if (!isUpgrading) {
			if (dao.isNameExists(name)) {
				PromptUtils.showShortToast(context, "电脑名称已存在！");
				et_name.setText("");
				return false;
			}

			if (dao.isMacExists(mac)) {
				PromptUtils.showShortToast(context, "物理地址已存在！");
				et_mac.setText("");
				return false;
			}
		}else{
			
		}
		return true;
	}
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;

		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	

	/**
	 * Adapter
	 * 
	 * @author wen
	 */
	private class MacAddrsAdapter extends BaseAdapter {

		private List<MacAddr> list;

		public MacAddrsAdapter(List<MacAddr> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder = null;
			if (convertView == null) {

				convertView = View.inflate(context,
						R.layout.activity_settings_listview_addr_item, null);
				TextView tv_name = (TextView) convertView
						.findViewById(R.id.tv_addr_name);
				TextView tv_mac = (TextView) convertView
						.findViewById(R.id.tv_addr_mac);

				holder = new ViewHolder();
				holder.tv_addr_name = tv_name;
				holder.tv_addr_mac = tv_mac;

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			MacAddr macAddr = list.get(position);
			holder.tv_addr_name.setText(macAddr.name);
			holder.tv_addr_mac.setText(macAddr.mac);

			return convertView;
		}
	}

	private class ViewHolder {
		TextView tv_addr_name;
		TextView tv_addr_mac;
	}

}
